package com.kongshidian.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.Product;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.view.AbsViewHolderAdapter;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 * 品牌列表
 */
@SuppressLint("HandlerLeak") 
public class BrandListActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{

	private String brandId = "";
	private String productCategoryId = "";
	private String brandName = "";
	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private int nowPage = 1;
	private List<Product> mBrands;
	private BrandListAdapter mAdapter;
	private RelativeLayout mEmptyRelat;
	private Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		brandId = getIntent().getStringExtra("brandId");
		productCategoryId = getIntent().getStringExtra("productCategoryId");
		brandName = getIntent().getStringExtra("brandName");
		setContentView(R.layout.activity_brand_list);
		getTitleBar().setTitle(brandName);
		mEmptyRelat = (RelativeLayout) findViewById(R.id.brand_empty_relat);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.brand_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new BrandListAdapter(this,R.layout.item_search_list);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();
		
		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent,
					View view, int position, long id) {
				Intent intent = new Intent(BrandListActivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", mAdapter.getData().get(position-1).getId()+"");
				startActivity(intent);
				
			}
			
		});

	}

	@Override
	public void onRefresh(int page) {
		updateBrandList(1, true);
	}
	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateBrandList(nowPage, false);
	}

	private void updateBrandList(final int pageNum,final boolean isRefresh){
		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(BrandListActivity.this);

					PageEntity<Product> entry = client.getBrandList(brandId,productCategoryId,pageNum, 10, "", "desc");
					int totlePage = entry.getTotalPages();

					mBrands = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						return;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mBrands = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		mLoadMoreProxy.loadDataActionComplete(true);
	}
	
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					mAdapter.update(mBrands);
					break;
				case 1:
					mAdapter.append(mBrands);
					break;

				default:
					break;
				}
			}
			
			
		}
		
		
	}
 	

//	@SuppressLint("HandlerLeak") 
//	final Handler mHandler = new Handler(){
//		public void dispatchMessage(android.os.Message msg) {
//			switch (msg.what) {
//			case 0:
//				mAdapter.update(mBrands);
//				break;
//			case 1:
//				mAdapter.append(mBrands);
//				break;
//
//			default:
//				break;
//			}
//		};
//	};
	private class BrandListAdapter extends AbsViewHolderAdapter<Product>{

		public BrandListAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {
			ImageView mImage = getViewFromHolder(R.id.item_search_image);
			TextView mNameText = getViewFromHolder(R.id.item_search_name_txt);
			TextView mPriceText = getViewFromHolder(R.id.item_search_price_txt);

			ImageLoader.getInstance().displayImage(itemData.getImage(), mImage);
			mNameText.setText(itemData.getName());
			mPriceText.setText("￥"+itemData.getPrice());
		}

	} 
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
